package com.tezign.intelligence.mini.dam.aifamilyconsultant.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.UserStatusEnum;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.req.LoginReq;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.ResponseBean;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.req.UserUpdateReq;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.resp.UserVO;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.UserTypeEnum;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.FamilyMember;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.User;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor.UserStore;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.IFamilyMemberService;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant.TOKEN_PREFIX;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author six
 * @since 2024-11-13
 */
@Api(tags = "用户管理")
@Slf4j
@CrossOrigin("*")
@RestController
@RequiredArgsConstructor
@RequestMapping(Constant.APPLICATION_NAME + "/user")
public class UserController {
	private final IUserService userService;

	private final IFamilyMemberService familyMemberService;

	private final RedisTemplate<String, Object> redisTemplate;


	/**
	 * 用户登录
	 *
	 * @return
	 * @throws
	 * @since 2024/11/16 22:49
	 */
	@PostMapping("/login")
	@ApiOperation(value = "用户登录")
	public ResponseBean<UserVO> login(@RequestBody @Valid LoginReq loginReq) {
		log.info("用户登录");
		String password = loginReq.getPassword();
		// md5加密
		String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
		User one = userService.lambdaQuery()
				.eq(User::getUserType, UserTypeEnum.FRONT.getValue())
				.eq(User::getName, loginReq.getName())
				.eq(User::getPassword, md5Password)
				.last("limit 1").one();
		if (one == null) {
			return new ResponseBean<UserVO>().exception(UserStatusEnum.ERROR.addErrorMsg("用户名或密码错误"));
		}
		// 生成token
		String token = DigestUtils.md5DigestAsHex((loginReq.getName() + System.currentTimeMillis()).getBytes());
		// 存入redis 3天有效
		redisTemplate.opsForValue().set(String.format(TOKEN_PREFIX, one.getId()), token, 3, TimeUnit.DAYS);
		return getUserVOResponseBean(one, token);
	}

	// 获取用户信息
	@GetMapping("")
	@ApiOperation(value = "获取用户信息")
	public ResponseBean<UserVO> info() {
		Long userId = UserStore.getUserId();
		User one = userService.getById(userId);
		if (one == null) {
			return new ResponseBean<UserVO>().exception();
		}
		String token = String.valueOf(redisTemplate.opsForValue().get(String.format(TOKEN_PREFIX, one.getId())));
		return getUserVOResponseBean(one, token);

	}

	@ApiOperation("用户注册")
	@PostMapping("/register")
	public ResponseBean<Boolean> register(@RequestBody @Valid LoginReq user) {
		log.info("用户注册");
		// 查询用户名是否存在
		User one = userService.lambdaQuery().eq(User::getName, user.getName()).last("limit 1").one();
		if (one != null) {
			return new ResponseBean<Boolean>().exception(UserStatusEnum.ERROR.addErrorMsg("用户名已存在"));
		}

		String password = user.getPassword();
		// md5加密
		String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
		user.setPassword(md5Password);
		User copied = BeanUtil.copyProperties(user, User.class);
		boolean save = userService.save(copied);
		return new ResponseBean<Boolean>().success(save);
	}

	@ApiOperation("编辑用户信息")
	@PostMapping("/update")
	public ResponseBean<Boolean> update(@RequestBody @Valid UserUpdateReq req) {
		log.info("编辑用户信息 req={}", JSONUtil.toJsonStr(req));

		String md5Pwd = null;
		if(!StringUtils.isEmpty(req.getPassword())) {
			md5Pwd = DigestUtils.md5DigestAsHex(req.getPassword().getBytes());
		}

		boolean update = userService.lambdaUpdate().eq(User::getId, req.getId())
				.set(!StringUtils.isEmpty(req.getSex()), User::getSex, req.getSex())
				.set(!StringUtils.isEmpty(req.getName()), User::getName, req.getName())
				.set(!StringUtils.isEmpty(req.getPassword()), User::getPassword, md5Pwd)
				.set(Objects.nonNull(req.getBirthday()), User::getBirthday, req.getBirthday())
				.update();
		return new ResponseBean<Boolean>().success(update);
	}


	private ResponseBean<UserVO> getUserVOResponseBean(User one, String token) {
		UserVO userVO = BeanUtil.copyProperties(one, UserVO.class);
		userVO.setToken(token);
		if (one.getActiveFamilyId() != null && one.getActiveFamilyId() > 0) {
			FamilyMember familyMember = familyMemberService.lambdaQuery().eq(FamilyMember::getUserId, one.getId()).eq(FamilyMember::getFamilyId, one.getActiveFamilyId()).last("limit 1").one();
			if (familyMember != null) {
				userVO.setRole(familyMember.getRole());
			}
		}
		return new ResponseBean<UserVO>().success(userVO);
	}
}
